#include "CacheManager.h"
#include "Cache.h"
#include <iostream>
#include <stack>

vector<Cache> CacheManager::_cacheList;
string CacheManager::_CaheManagerfilename;

void CacheManager::initCache(size_t sz,const string &filename)
{
    CacheManager::_CaheManagerfilename=filename;
    /* std::cout<<_CaheManagerfilename<<std::endl; */
    for(size_t i=0;i!=sz;i++)
    {
        /* std::cout<<i<<std::endl; */
        Cache cache;
        cache.readFromFile(filename);    
        CacheManager::_cacheList.push_back(cache);
        /* std::cout<<CacheManager::_cacheList.size()<<std::endl; */
    }
}

Cache& CacheManager::getCache(size_t idx)
{
    return _cacheList[idx];
}

void CacheManager::periodicUpdateCaches()
{
    //先对每个cache更新
    for(size_t idx=0;idx!=_cacheList.size();idx++){
        _cacheList[idx].selfUpdate();
    }
    //将每个cache的部分写入0号cache
    for(size_t idx=1;idx!=_cacheList.size();idx++)
    {
        //元素从后向前传递，保证前段的元素依旧高优先级
        if(!_cacheList[idx].getLRUlist().empty()){
            stack<pair<string,string>> st;
            for(auto& elem:_cacheList[idx].getLRUlist()){
                st.push(elem);
            }
            while(!st.empty()){
                _cacheList[0].addElement(st.top().first,st.top().second);
                st.pop();
            }
        }
    }
    //再次更新0号
    _cacheList[0].selfUpdate();
    //覆盖其他cache
    for(size_t idx=1;idx!=_cacheList.size();idx++){
        _cacheList[idx].update(_cacheList[0]);
    }
    _cacheList[0].writeToFile(_CaheManagerfilename);
    cout<<"The Cache has been updated!"<<endl;
}
